﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.ApplicationPages;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration;
using System.Web;
using System.Collections;
using System.Collections.Generic;

namespace SpugPt.DataConnManager
{
    public partial class EditDataConnection : GlobalAdminPageBase
    {
        private bool _isNew = true;
        SPWebApplication _webApp;



        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event to initialize the page.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            ((DialogMaster)this.Page.Master).OkButton.Click += new EventHandler(OkButton_Click);

            base.OnInit(e);

        }
        /// <summary>
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            this.btDelete.Click += new EventHandler(btDelete_Click);
            GetValues();
            _webApp = Helper.GetWebApp(HttpContext.Current.Request.QueryString["WebId"]);
        }
        /// <summary>
        /// Handles the Click event of the btDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void btDelete_Click(object sender, EventArgs e)
        {
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                operation.LeadingHTML = "Operation";
                operation.Begin();
                try
                {
                    DeleteValues();
                }
                finally
                {
                    operation.EndScript("window.close();");
                }
            }
        }
       
        /// <summary>
        /// Raises the <see cref="E:PreRender"/> event.
        /// </summary>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected override void OnPreRender(EventArgs e)
        {

            base.OnPreRender(e);
            GetValues();
        }
        /// <summary>
        /// Handles the Click event of the OkButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void OkButton_Click(object sender, EventArgs e)
        {
            if (_isNew  && FoundKey(txtName.Text.Trim()))
            {
                lblErrorMessage.Text = "This key name already exists. Please create a new one.";
                return;
            }

                
            using (SPLongOperation operation = new SPLongOperation(this))
            {
                //operation.LeadingHTML = "Operation";
                operation.Begin();
                try
                {
                    if (_isNew){

                        
                        InsertValues();
                    }
                        
                    else
                        UpdateValues();
                }
                finally
                {
                    operation.EndScript("window.close();");
                }
            }

        }
       
        /// <summary>
        /// Gets the key prefix of Key.
        /// </summary>
        /// <returns></returns>
        public string Prefix
        {
            get {return Helper.PREFIX;}
        }
        /// <summary>
        /// Gets the values.
        /// </summary>
        private void GetValues()
        {
            if (!String.IsNullOrEmpty(Context.Request.QueryString["Name"]))
            {
                txtName.Text = Context.Request.QueryString["Name"].ToString();
                _isNew = false;
            }
            if (!String.IsNullOrEmpty(Context.Request.QueryString["Value"]))
                txtValue.Text = Context.Request.QueryString["Value"].ToString();

          
            txtName.ReadOnly = !_isNew;
            if (String.IsNullOrEmpty(Context.Request.QueryString["EDIT"]))
            {
                this.lblDescription.Text = " New key";
                this.btDelete.Visible = false;
            }
            else
            {
                this.lblDescription.Text = " Edit key";
                this.btDelete.Visible = true;
            }
        }

        /// <summary>
        /// Cleans the values.
        /// </summary>
        private void CleanValues()
        {
            txtName.Text = txtName.Text.Trim();
            txtValue.Text = txtValue.Text.Trim();

        }
        /// <summary>
        /// Gets the key.
        /// </summary>
        /// <returns></returns>
        private string GetKey()
        {
            return String.Concat(Helper.PREFIX, txtName.Text);
        }
        /// <summary>
        /// Inserts the values.
        /// </summary>
        void InsertValues()
        {
            CleanValues();
            string key = GetKey();
            
            if (_webApp != null)
            {

                if (!FoundKey(key))
                {
                    _webApp.Properties.Add(key, txtValue.Text);
                    _webApp.Update();
                }

            }
        }
        /// <summary>
        /// Deletes the values.
        /// </summary>
        void DeleteValues()
        {
            string key = GetKey();
            if (_webApp != null && _webApp.Properties.ContainsKey(key))
            {
                _webApp.Properties.Remove(key);
                _webApp.Update();
            }
        }
        /// <summary>
        /// Updates the values.
        /// </summary>
        void UpdateValues()
        {
            CleanValues();
            string key = GetKey();

            if (_webApp != null)
            {
                string find = key;
                foreach (DictionaryEntry Item in _webApp.Properties)
                {
                    if (Item.Key.ToString() == key)
                    {
                        _webApp.Properties[key] = txtValue.Text.Trim();
                        _webApp.Update();
                        break;
                    }
                }

            }
        }

        /// <summary>
        /// Validates the duplicate key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        bool FoundKey(string key)
        {
            string find = String.Concat(Helper.PREFIX, key);
            bool found = false;
            foreach (DictionaryEntry Item in _webApp.Properties)
            {
                if (Item.Key.ToString().ToUpper() == find.ToUpper())
                {
                    found = true;
                    break;
                }
            }
            return found;
        }
      
    }
}
